require 'json'

class ImagesController < ApplicationController
  include Painter

#  caches_action :showfile

  before_filter :login_required, :only => [:new, :edit, :destroy, :painter]

  # GET /images
  # GET /images.xml
  def index
    @images = Image.find(:all)

    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @images.to_xml }
    end
  end

  # GET /images/1
  # GET /images/1.xml
  def show
    @image = Image.find(params[:id])

    respond_to do |format|
      format.html # show.rhtml
      format.xml  { render :xml => @image.to_xml }
    end
  end

  # GET /images/new
  def new
    @image = Image.new
  end

  # GET /images/1;edit
  def edit
    @image = Image.find(params[:id])
  end

  # POST /images
  # POST /images.xml
  def create
    @image = Image.new(params[:image])

    respond_to do |format|
      @image.user_id = current_user.id
      if !@image.file.blank?
        if  (@image.file.size != 0)
          if ( @image.file.size <= 3145728 )
            if ["image/jpeg", "image/pjpeg", "image/gif", "image/png", "image/x-png"].include? @image.content_type
              if @image.save
                flash[:notice] = 'Image was successfully created.'
                format.html { redirect_to image_url(@image) }
                format.xml  { head :created, :location => image_url(@image) }
              else
                format.html { render :action => "new" }
                format.xml  { render :xml => @image.errors.to_xml }
              end
            else
              flash[:error] = 'File have to be an image!'
              format.html { render :action => "new" }
              format.xml  { render :xml => @image.errors.to_xml }
            end
          else
            flash[:error] = 'File can\'t be greater than 3mb. Sorry'
            format.html { render :action => "new" }
            format.xml  { render :xml => @image.errors.to_xml }
          end
        else
          flash[:error] = 'File can\'t be blank'
          format.html { render :action => "new" }
          format.xml  { render :xml => @image.errors.to_xml }
        end
      else
        flash[:error] = "Unable to upload the file you selected, please try again."
        format.html { render :action => "new" }
        format.xml  { render :xml => @image.errors.to_xml }
      end
    end

  end

  # PUT /images/1
  # PUT /images/1.xml
  def update
    @image = Image.find(params[:id])

    respond_to do |format|
      if @image.update_attributes(params[:image])
        flash[:notice] = 'Image was successfully updated.'
        format.html { redirect_to image_url(@image) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @image.errors.to_xml }
      end
    end
  end

  # DELETE /images/1
  # DELETE /images/1.xml
  def destroy
    @image = Image.find(params[:id])
    @image.destroy

    respond_to do |format|
      format.html { redirect_to images_url }
      format.xml  { head :ok }
    end
  end

   def showfile
    @data = Image.find(params[:id])
    @file = @data.file
     disposition = 'inline'

     send_data(@file, :type     => @data.content_type,
                 :filename => @data.file_name,
                 :disposition => disposition)

   end

   def save_image
     painterHash = JSON.parse(params[:data])
     drawElems = []
     painterHash.each do |elem|
       drawElems << DrawElem.new(elem)
     end
     image = Image.find(params[:id])
     data = Magick::Image.from_blob(image.file).first
     gc = Magick::Draw.new
     drawElems.each do |elem|
       elem.paint(gc)
     end
     if drawElems.length > 0
       gc.draw(data)
       image.file = data.to_blob
       if image.save
         flash[:flash] = 'Image was successfully saved'
       else
         flash[:flash] = 'Error while saving image'
       end
     end
     respond_to do |format|
       format.html { render :nothing => true }
     end
   end

   def painter
     @imageRec = Image.find(params[:id])
     @image = Magick::Image.from_blob(@imageRec.file).first

     respond_to do |format|
       format.html { render :action => 'painter', :layout => false }
     end
   end

  def execute_filter
     filter = Filter.find(params[:id])
     image = Image.find(params[:imgid])
     name =  "#{RAILS_ROOT}/public/images/tmp/#{image.file_name}--#{Time.now.to_i.to_s}"
     img_name = filter.execute(image,name)
     if request.xhr?
       page :update do
         page.replace_html 'img_update', "<script>updateImage('#{name}')</script>"
       end
     end
   end
end
